package com.uidt.project.ptsj.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.uidt.common.constant.Constants;
import com.uidt.common.utils.DateUtils;
import com.uidt.common.utils.SecurityUtils;
import com.uidt.common.utils.StringUtils;
import com.uidt.common.utils.uuid.UUID;
import com.uidt.framework.security.LoginUser;
import com.uidt.framework.web.domain.AjaxResult;
import com.uidt.project.ptsj.domain.*;
import com.uidt.project.ptsj.mapper.*;
import com.uidt.project.ptsj.obj.InspectionForPage;
import com.uidt.project.ptsj.service.IPtsjCardInfoService;
import com.uidt.project.system.domain.SysDept;
import com.uidt.project.system.mapper.SysDeptMapper;
import com.uidt.project.system.service.ISysDeptService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.uidt.project.ptsj.service.IInspectionService;

/**
 * 巡检信息Service业务层处理
 *
 * @author uidt
 * @date 2024-08-12
 */
@Service
public class InspectionServiceImpl implements IInspectionService {
    private static final Logger log = LoggerFactory.getLogger(InspectionServiceImpl.class);
    @Autowired
    private InspectionMapper inspectionMapper;
    @Autowired
    private ScoreRecordMapper scoreRecordMapper;
    @Autowired
    private ProblemMapper problemMapper;
    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Autowired
    private PlaceInfoMapper placeInfoMapper;
    @Autowired
    private HouseInfoMapper houseInfoMapper;

    @Autowired
    private IPtsjCardInfoService cardInfoService;

    @Autowired
    private EventInfoMapper ptsjEventInfoMapper;

    @Autowired
    private PtsjCardInfoMapper ptsjCardInfoMapper;

    @Autowired
    private PtsjFileMapper fileMapper;

    @Autowired
    private ISysDeptService sysDeptService;

    /**
     * 查询巡检信息
     *
     * @param id 巡检信息主键
     * @return 巡检信息
     */
    @Override
    public AjaxResult selectInspectionById(Long id) {

        Map<String,Object> map = new HashMap<>();
        // 巡检记录
        Inspection inspection = inspectionMapper.selectInspectionById(id);

        // 巡检记录附件
        PtsjFile file = new PtsjFile();
        file.setGlid(String.valueOf(inspection.getId()));
        file.setTablename("ptsj_inspection");
        List<PtsjFile> fileList = fileMapper.selectPtsjFileList(file);
        inspection.setInspFiles(fileList);

        map.put("inspection",inspection);

        // 相关加扣分记录
        ScoreRecord scoreRecord = new ScoreRecord();
        scoreRecord.setInspectionId(inspection.getId());
        List<ScoreRecord> scoreRecords = scoreRecordMapper.selectScoreRecordList(scoreRecord);

        map.put("scoreRecords",scoreRecords);

        // 挂牌记录
        PtsjCardInfo cardInfo = new PtsjCardInfo();
        cardInfo.setGlid(String.valueOf(inspection.getId()));
        List<PtsjCardInfo> cardInfoList = ptsjCardInfoMapper.selectPtsjCardInfoList(cardInfo);

        map.put("cardInfoList",cardInfoList);

        return AjaxResult.success(map);
    }

    /**
     * 查询巡检信息列表
     *
     * @param ptsjInspection 巡检信息
     * @return 巡检信息
     */
    @Override
    public List<Inspection> selectInspectionList(Inspection ptsjInspection) {

        LoginUser user = SecurityUtils.getLoginUser();

        if(!user.getUser().getDept().getDeptName().equals("业主")){
            // 自定义datascope，根据用户角色的自定义数据权限，拼接查询sql
            if(user!=null){
                StringBuilder sqlDeptcode = sysDeptService.getDeptAuthByCodeForEvent(user.getUser());
                if(sqlDeptcode!=null){
                    StringBuilder dataScope = new StringBuilder();
                    dataScope.append("(").append("dept_code like '").append(sqlDeptcode).append("'").append(")");
                    Map<String,Object> paramMap = new HashMap<>();
                    paramMap.put("MydataScope","("+dataScope.toString()+")");
                    ptsjInspection.setParams(paramMap);
                }
            }

        }


//        List<>
//        user.getUser().getRoles()


        return inspectionMapper.selectInspectionList(ptsjInspection);
    }

    /**
     * 新增巡检信息
     *
     * @param ptsjInspection 巡检信息
     * @return 结果
     */
    @Override
    public int insertInspection(Inspection ptsjInspection) {
        return inspectionMapper.insertInspection(ptsjInspection);
    }

    /**
     * 修改巡检信息
     *
     * @param ptsjInspection 巡检信息
     * @return 结果
     */
    @Override
    public int updateInspection(Inspection ptsjInspection) {
        ptsjInspection.setUpdateTime(DateUtils.getNowDate());
        return inspectionMapper.updateInspection(ptsjInspection);
    }

    /**
     * 批量删除巡检信息
     *
     * @param ids 需要删除的巡检信息主键
     * @return 结果
     */
    @Override
    public int deleteInspectionByIds(Long[] ids) {
        return inspectionMapper.deleteInspectionByIds(ids);
    }

    /**
     * 删除巡检信息信息
     *
     * @param id 巡检信息主键
     * @return 结果
     */
    @Override
    public int deleteInspectionById(Long id) {
        return inspectionMapper.deleteInspectionById(id);
    }

    @Override
    public int addInspection(InspectionForPage request) {

        Date now = DateUtils.getNowDate();
//        log.info(request.toJSONString());
        Inspection inspection = new Inspection();
        String placeId = request.getPlaceCode(); //场所ID
        String placeName = request.getPlaceName();
        String roomId = request.getRoomId(); //房源码
        String roomName = request.getRoomName();
        LoginUser user = SecurityUtils.getLoginUser();
        String username = user.getUsername();
        String deptName = user.getUser().getDept().getDeptName();

        // 获取对应的场所信息
        PlaceInfo placeInfo = placeInfoMapper.selectPlaceInfoByPlaceCode(placeId);

        inspection.setWorker(user.getUsername());
        inspection.setDepartment(deptName);
        inspection.setInspectionTime(now);
        inspection.setCreatedBy(user.getUsername());
        inspection.setCreatedTime(now);
        inspection.setRoomId(roomId);
        inspection.setPlaceCode(placeId);
        inspection.setRoomName(roomName);
        inspection.setPlaceName(placeName);
        inspection.setRoomProblem(request.getRoomProblem());

        inspection.setDeptCode(user.getUser().getDept().getDeptcode());

        log.info(JSONObject.toJSONString(inspection));

        int count = inspectionMapper.insertInspection(inspection);
        // 巡检记录id
        long inspectionId = inspection.getId();

        /*巡检记录附件新增*/
        if(request.getInspFiles()!=null && request.getInspFiles().size()>0){
            for(PtsjFile ptsjFile:request.getInspFiles()){
                ptsjFile.setTablename("ptsj_inspection");
                ptsjFile.setGlid(String.valueOf(inspectionId));
                fileMapper.insertPtsjFile(ptsjFile);
            }
        }

        //挂牌
        if (StringUtils.isNotEmpty(request.getCardType())) {

            PtsjCardInfo cardInfo = new PtsjCardInfo();
            cardInfo.setId(UUID.randomUUID().toString());
            cardInfo.setCardItem(request.getCardItem());
            cardInfo.setCardType(request.getCardType());
            cardInfo.setCardBz(request.getCardBz());
            cardInfo.setCardStatus(1l);
            cardInfo.setGlid(String.valueOf(inspectionId));
            cardInfo.setCreatedBy(user.getUsername());
            cardInfo.setRectStartTime(request.getRectStartTime());
            cardInfo.setRectEndTime(request.getRectEndTime());
            // 0待核查，1已整改、2未整改
            cardInfo.setRectQk("0");
            cardInfo.setCreatedBy(user.getUsername());
            cardInfo.setCreatedTime(now);
            cardInfoService.insertPtsjCardInfo(cardInfo);

            // 对巡检记录的更新
            inspection.setCardItem(request.getCardItem());
            inspection.setCardType(request.getCardType());
            inspection.setCardBz(request.getCardBz());
            inspection.setRectStartTime(request.getRectStartTime());
            inspection.setRectEndTime(request.getRectEndTime());
//            inspection.setCardStatus(1l);

             // 对场所挂牌信息的更新
            switch (request.getCardType()){
                case "蓝牌":
                    placeInfo.setBlue(placeInfo.getBlue()+1);
                    break;
                case "黄牌":
                    placeInfo.setYellow(placeInfo.getYellow()+1);
                    break;
                case "红牌":
                    placeInfo.setRed(placeInfo.getRed()+1);
                    break;
            }

            HouseInfo houseInfo = new HouseInfo();
            houseInfo.setHouseCode(inspection.getRoomId());
            houseInfo.setCardstatus("1");
            houseInfoMapper.updateHouseInfo(houseInfo);
        }

        long id = inspectionId;
        long score = 0L;
        //加分
        if (request.getScoreList()!=null && request.getScoreList().size()>0) {
            List<ScoreRecord> scoreList = request.getScoreList();
            for (int i = 0; i < scoreList.size(); i++) {
                ScoreRecord record = scoreList.get(i);
                ScoreRecord scoreRecord = new ScoreRecord();
                scoreRecord.setInspectionId(id);
                scoreRecord.setCreatedBy(username);
                scoreRecord.setCreatedTime(now);
                scoreRecord.setScore(record.getScore());
                scoreRecord.setScoreRemark(record.getScoreRemark());
                scoreRecord.setScoreType(record.getScoreType());
                scoreRecord.setScoreItem(record.getScoreItem());
                scoreRecordMapper.insertScoreRecord(scoreRecord);
                if(record.getScoreType().equalsIgnoreCase("加分") ){
                    score  = score + record.getScore();
                }else{
                    score = score - record.getScore();
                }
            }
            // 对巡检记录的加扣分记录
            inspection.setScore((int) score);
            // 对于场所的加扣分修改
            placeInfo.setScore(placeInfo.getScore()+score);

        }
        SysDept xhDept = sysDeptService.getXhDept(user.getUser().getDept().getDeptcode().split("-")[0]);
        if (request.getEventList()!=null && request.getEventList().size()>0) {
            List<EventInfo> eventList = request.getEventList();
            for (int i = 0; i < eventList.size(); i++) {
                EventInfo ptsjEventInfo = eventList.get(i);
                String eventId = Constants.EVENT_PREFIX+DateUtils.dateTimeNow(DateUtils.YYYYMMDDHHMMSS);

                ptsjEventInfo.setEventId(eventId);
                ptsjEventInfo.setPlaceCode(placeId);
                ptsjEventInfo.setPlaceName(placeName);
                ptsjEventInfo.setRoomName(roomName);
                ptsjEventInfo.setRoomNum(roomId);
                ptsjEventInfo.setStatus("1");
                ptsjEventInfo.setGlid(String.valueOf(inspectionId));
                ptsjEventInfo.setGltable("ptsj_inspection");
                ptsjEventInfo.setProcDept(xhDept.getDeptName());
                ptsjEventInfo.setProcDeptCode(xhDept.getDeptcode());
                ptsjEventInfo.setFeedbackUnit(user.getUser().getDept().getDeptName());
                ptsjEventInfo.setEventSource("内部流转");
                ptsjEventInfo.setFeedbackPerson(user.getUsername());
                ptsjEventInfo.setFeedbackPhone(user.getUser().getPhonenumber());
                ptsjEventInfo.setCreatedTime(new Date());
                ptsjEventInfo.setCreatedBy(user.getUserId().toString());
                int count1 = ptsjEventInfoMapper.insertEventInfo(ptsjEventInfo);
                Long glid= ptsjEventInfo.getId();
                // 插入附件
                if(count1!=0 && ptsjEventInfo.getFileList()!=null && ptsjEventInfo.getFileList().size()>0){
                    for(PtsjFile ptsjFile:ptsjEventInfo.getFileList()){
                        ptsjFile.setTablename("ptsj_event_info");
                        ptsjFile.setGlid(String.valueOf(glid));
                        fileMapper.insertPtsjFile(ptsjFile);
                    }
                }
//                Problem problem = new Problem();
//                problem.setInspectionId(id);
//                problem.setCreatedBy(username);
//                problem.setCreatedTime(DateUtils.getNowDate());
//                problem.setProblemContent(record.getString("problemContent"));
//                problem.setProblemType(record.getString("problemType"));
//                problemMapper.insertProblem(problem);
            }
        }
        if(score != 0) {
            placeInfoMapper.addScore(placeId,score);
        }

        placeInfoMapper.updatePlaceInfo(placeInfo);
        inspectionMapper.updateInspection(inspection);

        return (int)id;
    }

    @Override
    public int applyCard(Inspection inspection) {
        //修改场所挂牌数
        String cardType = inspection.getCardType();
        String placeCode = houseInfoMapper.selectHouseInfoByHouseCode(inspection.getRoomId()).getPlaceCode();
        System.out.println("=============:" + cardType + ":" + placeCode);
        placeInfoMapper.addCard(Integer.valueOf(cardType),placeCode);
        //修改巡检记录挂牌状态
        inspectionMapper.closeCardStatus(inspection.getId());
        //修改房间挂牌状态
        houseInfoMapper.changeCardStatus(inspection.getRoomId());
        return 1;
    }
}
